<?php
namespace App\Admin\Controllers\Products;

use App\Importer\Products\SkuPacking\SkuPackingImporter;
use App\Models\Basics\PackingBox;
use App\Models\Product\ProductPacking;
use App\Models\Product\ProductPackingBox;
use App\Models\Product\ProductSku;
use App\Util\RExcel;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Illuminate\Support\Facades\DB;
class SkuPackingUploadController extends AdminController{

    protected $title = '产品包装资料上传';

    protected function grid()
    {
        $type = request('type');
        return view("products.sku-packing.index",compact('type'));
    }

    public function upload(Request $request){
        $file = $request->file('source_file');
        if ($file->isValid()) {
            $action = $request->get('action');
            $re = $this->{'_import'.$action}($file);
            if(is_array($re)) {
                if($re['flag']){
                    admin_toastr('文件：'.$re['data'].' 上传成功！');
                }else{
                    admin_toastr($re['data'],'error');
                }
            }else{
                return $re;
            }
        }else{
            admin_toastr('无效文件！','error');
        }
        return back()->withInput();
    }

    private function _importSkuPacking(UploadedFile $file){
        try{
            $data = Excel::toArray(new SkuPackingImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            DB::beginTransaction();
            $errors = [];
            $count = 1;
            $skuArr = [];
            foreach($data as $row){
                $count++;
                $sku = $row[0] ? trim($row[0]) : '';
                $shipWeight = is_null($row[1]) ? null : trim($row[1]);
                $packLong = $row[2] ? trim($row[2]) : '';
                $packWide = $row[3] ? trim($row[3]) : '';
                $packHigh = $row[4] ? trim($row[4]) : '';
                if(!$sku){
                    $errors[$count] = '必填项为空';
                    continue;
                }
                if(!in_array($sku,$skuArr)){
                    $skuArr[$count] = $sku;
                }else{
                    $errors[$count] = '重复记录';
                    continue;
                }
                $pSkuId = ProductSku::getValueByCode($sku,'id');
                if(!$pSkuId){
                    $errors[$count] = $sku.'系统不存在';
                    continue;
                }
                $pp = ProductPacking::query()->firstOrNew(['psku_id' => $pSkuId]);
                if(!is_null($shipWeight)){
                    $pp->ship_weight = $shipWeight;
                }
                if($packLong){
                    $pp->pack_long = $packLong;
                }
                if($packWide){
                    $pp->pack_wide = $packWide;
                }
                if($packHigh){
                    $pp->pack_high = $packHigh;
                }
                $pp->save();
            }
            DB::commit();
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            DB::rollBack();
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    private function _importSkuPackingShip(UploadedFile $file){
        try{
            $data = Excel::toArray(new SkuPackingImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            DB::beginTransaction();
            $errors = [];
            $count = 1;
            $skuArr = [];
            foreach($data as $row){
                $count++;
                $boxType = $row[0] ? trim($row[0]) : '';
                $sku = $row[1] ? trim($row[1]) : '';
                $boxLong = $row[2] ? trim($row[2]) : '';
                $boxWide = $row[3] ? trim($row[3]) : '';
                $boxHigh = $row[4] ? trim($row[4]) : '';
                $numPerBox = is_null($row[5]) ? null : trim($row[5]);
                $weightPerBox = is_null($row[6]) ? null : trim($row[6]);
                if(!$boxType || !$sku){
                    $errors[$count] = '必填项为空';
                    continue;
                }
                $key = $sku.'_'.$boxType;
                if(!in_array($key,$skuArr)){
                    $skuArr[$count] = $key;
                }else{
                    $errors[$count] = '重复记录';
                    continue;
                }
                $pSkuId = ProductSku::getValueByCode($sku,'id');
                if(!$pSkuId){
                    $errors[$count] = $sku.'系统不存在';
                    continue;
                }
                $packingBoxId = PackingBox::getIdByBoxType($boxType);
                if(!$packingBoxId){
                    $errors[$count] = $boxType.'系统不存在,请选择'.implode(',',PackingBox::options()->toArray());
                    continue;
                }
                $pp = ProductPackingBox::query()->firstOrNew(['psku_id' => $pSkuId,'packing_box_id' => $packingBoxId]);
                if(!is_null($numPerBox)){
                    $pp->num_per_box = $numPerBox;
                }
                if(!is_null($weightPerBox)){
                    $pp->weight_per_box = $weightPerBox;
                }
                if($boxLong){
                    $pp->box_long = $boxLong;
                }
                if($boxWide){
                    $pp->box_wide = $boxWide;
                }
                if($boxHigh){
                    $pp->box_high = $boxHigh;
                }
                $pp->save();
            }
            DB::commit();
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            DB::rollBack();
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    public function template(Request $request){
        $temp = $request->get('temp');
        $suffix = $request->get('suffix','xlsx');
        return Storage::disk('admin')->download("template/{$temp}-template.{$suffix}");
    }
}
